<template>
  <div style="background-color: white; margin-top: -5px">
    <van-sticky :offset-top="47">
      <el-alert
        :title="infoAlert.title"
        :type="infoAlert.type"
        center
        show-icon
        :closable="false"
        style="margin-bottom: 15px"
      ></el-alert>
    </van-sticky>
    <van-form @submit="submitForm">
      <van-field
        v-model="form.projectOn"
        label="项目编号"
        placeholder="立项表提交后自动生成"
        readonly
      />
      <van-field
        v-model="form.projectName"
        label="项目名称"
        placeholder="请输入项目名称"
        :rules="[{ required: true, message: '请输入项目名称' }]"
      />
      <DeptTreePicker
        ref="treePicker"
        v-model="form.deptId"
        label="所属部门"
        :rules="[{ required: true, message: '请选择归属部门' }]"
      />
      <van-field
        v-model="form.projectTime"
        label="立项时间"
        placeholder="请选择立项时间"
        @click="projectTimeFlag = true"
        :rules="[{ required: true, message: '立项时间不能为空' }]"
      />
      <van-calendar
        v-model="projectTimeFlag"
        @confirm="onConfirm($event, 'projectTimeFlag', 'projectTime')"
        :min-date="minDate"
        :max-date="maxDate"
      />
      <searchable-picker
        v-model="form.applyUser"
        :columns="userList"
        valueKey="userId"
        labelKey="userName"
        label="申请人"
        placeholder="请选择申请人"
        :rules="[{ required: true, message: '申请人不能为空' }]"
      />
      <searchable-picker
        v-model="form.chargeUser"
        multiSelect
        :columns="userList"
        valueKey="userId"
        labelKey="userName"
        label="负责人"
        placeholder="请选择负责人"
        :rules="[{ required: true, message: '负责人不能为空' }]"
      />
      <searchable-picker
        v-model="form.nature"
        :columns="dict.type.crm_order_nature"
        valueKey="value"
        labelKey="label"
        label="项目性质"
        placeholder="请选择项目性质"
        :rules="[{ required: true, message: '项目性质不能为空' }]"
      />
      <searchable-picker
        v-model="form.nature"
        :columns="dict.type.crm_order_contracts"
        valueKey="value"
        labelKey="label"
        label="签订单位"
        placeholder="请选择签订单位"
        :rules="[{ required: true, message: '签订单位不能为空' }]"
      />
      <van-field
        v-model="form.startTime"
        label="开始日期"
        placeholder="请选择开始日期"
        @click="startTimeFlag = true"
        :rules="[{ required: true, message: '开始日期不能为空' }]"
      />
      <van-calendar
        v-model="startTimeFlag"
        @confirm="onConfirm($event, 'startTimeFlag', 'startTime')"
        :min-date="minDate"
        :max-date="maxDate"
      />

      <van-field
        v-model="form.endTime"
        label="结束日期"
        placeholder="请选择结束日期"
        @click="endTimeFlag = true"
        :rules="[{ required: true, message: '结束日期不能为空' }]"
      />
      <van-calendar
        v-model="endTimeFlag"
        @confirm="onConfirm($event, 'endTimeFlag', 'endTime')"
        :min-date="minDate"
        :max-date="maxDate"
      />

      <searchable-picker
        v-model="form.customerId"
        :columns="customerList"
        valueKey="customerId"
        labelKey="customerName"
        label="客户名称"
        placeholder="点击选择客户名称"
        :rules="[{ required: true, message: '客户不能为空' }]"
      />

      <van-field
        v-model="form.projectSum"
        label="项目金额"
        type="number"
        placeholder="请输入项目金额"
        :rules="[{ required: true, message: '项目金额不能为空' }]"
      />

      <van-field
        v-model="form.profit"
        label="预计利润"
        type="number"
        placeholder="请输入预计利润"
        :rules="[{ required: true, message: '预计利润不能为空' }]"
      />

      <van-field
        v-model="form.profitMargin"
        label="利润率"
        type="number"
        placeholder="填写预计利润后自动计算"
        readonly
      />

      <van-field
        v-model="form.paymentTime"
        label="付款方式"
        placeholder="请输入付款方式"
        :rules="[{ required: true, message: '付款方式不能为空' }]"
      />
      <div class="details">
        <div class="details-header">项目预算成本费用支出</div>
        <van-collapse
          v-model="activeNames"
          class="product"
          v-for="(details, index) in form.detailsList"
          :key="index"
        >
          <van-collapse-item
            :title="'详情' + (index + 1)"
            :name="index + 1"
            icon="ellipsis"
            class="details-body"
          >
            <div class="details-button">
              <el-button type="text" @click="addExpenses(details, index)"
                >新增</el-button
              >
              <el-button
                type="text"
                style="color: red"
                @click="delExpenses(index)"
                v-if="details.flag !== '1'"
                >删除</el-button
              >
            </div>
            <van-field name="checkbox" label="无明细">
              <template #input>
                <van-checkbox
                  v-model="details.isRequired"
                  shape="square"
                  :disabled="
                    details.detailsAmount !== null &&
                    details.detailsAmount !== ''
                  "
                />
              </template>
            </van-field>
            <searchable-picker
              v-model="details.detailsType"
              :columns="dict.type.crm_fee_type"
              :readonly="details.flag === '1'"
              :disabled="details.isRequired"
              valueKey="value"
              labelKey="label"
              label="费用类型"
              placeholder="点击选择费用类型"
              :rules="[{ required: true, message: '费用类型不能为空' }]"
            />
            <van-field
              v-model="details.detailsName"
              label="费用名称"
              placeholder="请输入费用名称"
              :rules="[
                { required: !details.isRequired, message: '费用名称不能为空' },
              ]"
              :readonly="details.flag === '1'"
              :disabled="details.isRequired"
            />
            <van-field
              v-model="details.detailsDesc"
              label="费用描述"
              placeholder="请输入费用详情描述"
              :disabled="details.isRequired"
            />
            <van-field
              v-model="details.detailsAmount"
              label="预算合计"
              placeholder="请输入预算合计"
              :rules="[
                { required: !details.isRequired, message: '预算合计不能为空' },
              ]"
              :disabled="details.isRequired"
            />
            <van-field
              v-model="details.remark"
              label="备注"
              placeholder="请输入备注"
              :disabled="details.isRequired"
            />
          </van-collapse-item>
        </van-collapse>
        <div class="details-footer">
          <el-button
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="addExpenses(null)"
            >新增一项</el-button
          >
        </div>
        <div style="height: 10px; background-color: #eceff2"></div>
      </div>
      <van-field
        v-model="form.aggregationCharge"
        label="费用总计"
        placeholder="请输入备注"
        type="number"
        readonly
      />
      <van-field
        v-model="form.opinion"
        label="管理层意见"
        placeholder="请输入管理层意见"
      />
      <van-field name="uploader" label="文件上传" style="margin-bottom: 50px">
        <template #input>
          <file-upload v-model="form.url" />
        </template>
      </van-field>
      <div class="mobile-footer">
        <van-button
          native-type="submit"
          style="width: 49%; border-radius: 10px"
          @click="auditStatus = '0'"
          >暂存</van-button
        >
        <van-button
          type="info"
          native-type="submit"
          style="width: 49%; border-radius: 10px"
          @click="auditStatus = '1'"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import {
  listOrderRegister,
  addOrderRegister,
  updateOrderRegister,
  getOrderRegisterInfo,
} from "@/api/crm/orderRegister";

import { getUserListByStatus } from "@/api/system/user";

import { getCrmCustomerAllNoPage } from "@/api/crm/customer";

import { getOrder } from "@/api/crm/order";

export default {
  name: "OrderAdd",
  dicts: ["crm_order_nature", "crm_order_contracts", "crm_fee_type"],
  data() {
    return {
      minDate: new Date(2010, 0, 1),
      maxDate: new Date(2030, 0, 31),
      auditStatus: "",
      infoAlert: {
        type: "info",
        title: "待填写",
      },
      activeNames: [],
      form: {
        detailsList: [],
      },
      userList: [],
      productList: [],
      customerList: [],
      orderId: "",
      orderInfo: {},
      projectTimeFlag: false,
      startTimeFlag: false,
      endTimeFlag: false,
    };
  },
  watch: {
    "form.projectSum"() {
      // 计算公司明细
      let obj = this.form.detailsList?.find(
        (item) => "公司明细" === item.detailsName
      );
      obj.detailsAmount = (this.form.projectSum * 0.03).toFixed(2);
    },
    "form.detailsList": {
      handler(val) {
        if (!val) return;
        // 计算支出总金额
        const totalAmount = this.form.detailsList?.reduce((sum, item) => {
          const amount = parseFloat(item.detailsAmount) || 0;
          return sum + amount;
        }, 0);

        // 计算利润
        const profit = (this.form.projectSum - totalAmount).toFixed(2);
        this.$set(this.form, "profit", profit);

        // 计算利润率
        const profitMargin =
          this.form.projectSum > 0
            ? ((profit / this.form.projectSum) * 100).toFixed(2)
            : "0";
        this.$set(this.form, "profitMargin", profitMargin);

        this.form.aggregationCharge = totalAmount;
      },
      deep: true,
    },
  },
  async created() {
    this.orderId = this.$route.params.orderId;
    await this.getUserListByStatus();
    await this.getCrmCustomerAllNoPage();
    await this.getOrder();
    await this.getOrderRegisterInfo();
  },
  mounted() {},
  methods: {
    onConfirm(date, flag, fildes) {
      this[flag] = false;
      this.form[fildes] = `${date.getFullYear()}-${
        date.getMonth() + 1
      }-${date.getDate()}`;
    },
    async getOrder() {
      await getOrder(this.orderId).then((res) => {
        this.orderInfo = res.data;
      });
    },
    async getUserListByStatus() {
      await getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },
    async getCrmCustomerAllNoPage() {
      await getCrmCustomerAllNoPage({}).then((res) => {
        this.customerList = res.data;
      });
    },
    handleCheckboxChange(row, val) {
      row.isRequired = val ? "1" : "0";
    },
    async getOrderRegisterInfo() {
      await getOrderRegisterInfo({ orderId: this.orderId }).then((res) => {
        this.form = res.data;
        if (this.form) {
          // 根据审核状态设置提示
          switch (this.form.auditStatus) {
            case "0":
              this.infoAlert = { type: "info", title: "待提交" };
              break;
            case "1":
              this.infoAlert = { type: "warning", title: "待审核" };
              break;
            case "2":
              this.infoAlert = { type: "success", title: "审核通过" };
              break;
            case "3":
              this.infoAlert = { type: "error", title: "审核不通过" };
              break;
            case "4":
              this.infoAlert = { type: "warning", title: "审核中" };
              break;
          }

          this.form.chargeUser = this.form.chargeUser
            ? this.form.chargeUser.split(",")
            : null;
        
        } else {
          this.infoAlert = {
            type: "info",
            title: "待填写",
          };
          // 未填写则进行数据回显
          this.form = {
            nature: "1",
            laborContracts: "0",
            projectOn: "立项表提交后自动生成",
            deptId: this.$store.getters.deptId,
            projectName: this.orderInfo.orderName,
            customerId: this.orderInfo.customerId,
            applyUser: this.orderInfo.userId,
            chargeUser: [this.orderInfo.userId, ""],
            projectSum: this.orderInfo.planAmount,
            projectTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
            startTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
            detailsList: [
              {
                detailsName: "采购明细",
                detailsType: "0",
                detailsDesc: null,
                detailsAmount: null,
                remark: null,
                isRequired: "0",
                flag: "1",
              },
              {
                detailsName: "外援明细",
                detailsType: "1",
                detailsDesc: null,
                detailsAmount: null,
                remark: null,
                isRequired: "0",
                flag: "1",
              },
              {
                detailsName: "工单明细",
                detailsType: "2",
                detailsDesc: null,
                detailsAmount: null,
                remark: null,
                isRequired: "0",
                flag: "1",
              },
              {
                detailsName: "差旅明细",
                detailsType: "3",
                detailsDesc: null,
                detailsAmount: null,
                remark: null,
                isRequired: "0",
                flag: "1",
              },
              {
                detailsName: "软件研发明细",
                detailsType: "4",
                detailsDesc: null,
                detailsAmount: null,
                remark: null,
                isRequired: "0",
                flag: "1",
              },
              {
                detailsName: "税金明细",
                detailsType: "5",
                detailsDesc: null,
                detailsAmount: null,
                remark: null,
                isRequired: "0",
                flag: "1",
              },
              {
                detailsName: "公司明细",
                detailsType: "6",
                detailsDesc: "公司管理费",
                detailsAmount: (this.orderInfo.planAmount * 0.03).toFixed(2),
                remark: null,
                isRequired: "0",
                flag: "1",
              },
            ],
          };
        }
        this.buildActiveNames(this.form.detailsList);
        this.coverCheck(false);
      });
    },
    buildActiveNames(arr) {
      this.activeNames = [];
      for (let i = 1; i <= arr.length; i++) {
        this.activeNames.push(i);
      }
    },
    // 表单重置
    reset() {
      this.form = {
        nature: "1",
        laborContracts: "0",
        projectOn: "立项表提交后自动生成",
        deptId: this.$store.getters.deptId,
        projectName: this.orderInfo.orderName,
        customerId: this.orderInfo.customerId,
        applyUser: this.orderInfo.userId,
        chargeUser: [this.orderInfo.userId],
        projectSum: this.orderInfo.planAmount,
        projectTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
        startTime: this.parseTime(new Date(), "{y}-{m}-{d}"),
        detailsList: [
          {
            detailsName: "采购明细",
            detailsType: "0",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "外援明细",
            detailsType: "1",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "工单明细",
            detailsType: "2",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "差旅明细",
            detailsType: "3",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "软件研发明细",
            detailsType: "4",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "税金明细",
            detailsType: "5",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "公司明细",
            detailsType: "6",
            detailsDesc: "公司管理费",
            detailsAmount: (this.orderInfo.planAmount * 0.03).toFixed(2),
            remark: null,
            isRequired: "0",
            flag: "1",
          },
        ],
      };
      this.buildActiveNames(this.form.detailsList);
    },
    cancel() {
      this.reset();
      this.$emit("cancel");
    },
    addExpenses(scope, index) {
      if (scope) {
        this.form.detailsList.splice(index + 1, 0, {
          detailsName: scope.detailsName,
          detailsType: scope.detailsType,
          detailsDesc: null,
          detailsAmount: null,
          remark: null,
          isRequired: false,
          flag: "0",
        });
      } else {
        this.form.detailsList.push({
          detailsName: null,
          detailsDesc: null,
          detailsType: '7',
          detailsAmount: null,
          remark: null,
          isRequired: false,
          flag: "0",
        });
      }

      this.buildActiveNames(this.form.detailsList);
    },
    delExpenses(index) {
      this.form.detailsList.splice(index, 1);
    },
    /** 查询商机项目立项列表 */
    getList() {
      this.loading = true;
      listOrderRegister(this.queryParams).then((response) => {
        this.orderRegisterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    coverCheck(flag = true) {
      if (flag) {
        this.form.detailsList.forEach((item) => {
          item.isRequired = item.isRequired ? "1" : "0";
        });
      } else {
        this.form.detailsList.forEach((item) => {
          item.isRequired = item.isRequired === "1";
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.form.orderId = this.orderInfo.orderId;
      this.form.chargeUser = this.form.chargeUser.join(",");
      this.form.auditStatus = this.auditStatus;
      this.coverCheck();
      if (this.form.orderRegisterId != null) {
        updateOrderRegister(this.form).then((response) => {
          this.$toast.success("修改成功");
          this.getOrderRegisterInfo();
        });
      } else {
        addOrderRegister(this.form).then((response) => {
          this.$toast.success("新增成功");
          this.getOrderRegisterInfo();
        });
      }
    },
  },
};
</script>

<style scoped  lang="scss">
.submitButton {
  width: 95%;
  height: 50px;
  position: fixed;
  top: 90%;
  left: 10px;
}

::v-deep .van-collapse-item__content {
  padding: 0;
}

::v-deep .product .van-collapse-item__title {
  background-color: #eceff2;
  padding: 5px 16px;
}

.details {
  border-bottom: 1px solid #eceff2;

  .details-header {
    padding: 10px 16px 3px;
    color: #323233;
    font-size: 14px;
    line-height: 24px;
    background-color: #fff;
  }

  .details-footer {
    text-align: center;
    .el-button--text {
      font-size: 18px;
    }
  }

  .details-body {
    position: relative;
  }

  .details-button {
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 35px;
  }
}
</style>